package com.chalk.service.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.chalk.common.util.Result;
import com.chalk.dao.SignDao;
import com.chalk.model.Sign;
import com.chalk.service.MemberService;
import com.chalk.service.SignService;
import com.chalk.util.DateUtil;
import com.chalk.util.MapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author glq
 * @since 2020-12-17
 */

@Service
public class SignServiceImpl extends ServiceImpl<SignDao, Sign> implements SignService {

    @Autowired
    MemberService memberService;

    @Override
    public int addSign(Sign entity) {
        return baseMapper.insert(entity);
    }

    @Override
    public int updateSign(Sign entity) {
        return baseMapper.updateById(entity);
    }


    @Override
    public int deleteSign(Integer id) {
        return baseMapper.deleteById(id);
    }

    @Override
    public Result memberSign(String memberId) {
        Boolean f = false;
        //构造器
        EntityWrapper<Sign> wrapper = new EntityWrapper<>();
        wrapper.eq("member_id", memberId);
        wrapper.eq("is_delete", 0);
        wrapper.like("create_time", DateUtil.getDateString());
        Sign sign = selectOne(wrapper);
        if (sign != null) {
            return Result.fail("你今天已经签到了，无需重复签到！");
        } else {
            Sign s = new Sign();
            s.setMemberId(memberId);
            s.setCreateTime(LocalDateTime.now());
            f = insert(s);
            memberService.updateIntegral(10, "add", memberId);//增加10积分

        }
        if (f) {
            return Result.success("签到成功！积分+10");
        } else {
            return Result.success("签到失败！");
        }

    }

    @Override
    public Page<Sign> memberSignPage(Map<String, Object> map) {
        Integer page = MapUtil.getPage(map);
        Integer size = MapUtil.getSize(map);
        String memberId = (String) map.get("memberId");

        List<String> desc=new ArrayList<>();
        desc.add("create_time");

        Page<Sign> signPage = new Page<>(page, size);

        EntityWrapper<Sign> wrapper = new EntityWrapper<>();
        wrapper.eq("member_id", memberId);
        wrapper.orderDesc(desc);
        return selectPage(signPage,wrapper);
    }
}
